/*
 * @Author: DaTree
 * @Date: 2020-11-16 10:44:16
 * @LastEditTime: 2020-11-19 22:21:31
 * @LastEditors: DaTree
 * @Description: DaTreeEdit
 * @FilePath: \services\src\controller\routers.js
 * @天将降大任于是人也，必先苦其心志，劳其筋骨，饿其体肤，空乏其身，行拂乱其所为。 ——《孟子•告子下》
 * @symbol_custom_string_obkoro1_copyright: Copyright ${now_year} DaTree
 */
//routers.js  Api 核心路由
import express from 'express'
import requireContext from 'require-context'

import bodyParser from 'body-parser'
import chalk from 'chalk' // 紫色字体
import path from 'path'
import linq from 'linq'
const jsonParser = bodyParser.json()
const mockDir = path.join(process.cwd(), 'src/controller/modules')
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = requireContext(mockDir, false, /\.js$/)
let mocks = []
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file

modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.ts' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  console.log(
    chalk.bgBlackBright(
      `\n 读取: ${moduleName} 获取到 ${value.default.length}个路由。 `
    )
  )
  mocks = mocks.concat(value.default)
}, {})

// mock路由校验
console.log(chalk.bgBlueBright(`\n 开始校验路由url。 `))
let repeatFlag = false
mocks.forEach((route) => {
  const repeatRoute = linq
    .from(mocks)
    .where((x) => x.url === route.url)
    .toArray()
  if (repeatRoute.length > 1) {
    repeatFlag = true
    console.log(chalk.bgRedBright(`\n 路由${route.url}出现重复，请排查代码。 `))
  }
})
if (repeatFlag) {
  console.log(chalk.bgMagentaBright(`\n 重复的路由express会默认加载第一个。`))
} else {
  console.log(chalk.bgCyanBright(`\n 路由url校验通过。 `))
}

const router = express.Router()
// 此处加载的中间件也可以自动更新
// router.use(express.static('public'))
mocks.forEach((x) => {
  try {
    router[x.type](x.url, jsonParser, function (req, res) {
      res.send(x.response(req))
    })
  } catch (e) {
    console.log(
      chalk.yellowBright(
        `\n 警告：加载mock路由失败: ${JSON.stringify(x.default)} `
      )
    )
    console.log(
      chalk.yellowBright(
        `\n [${new Date().valueOf()}]—————————————————————begin:错误信息———————————————————————`
      )
    )
    console.log(chalk.yellowBright(e))
    console.log(
      chalk.yellowBright(
        `\n [${new Date().valueOf()}]———————————————————————end:错误信息———————————————————————`
      )
    )
  }
})

module.exports = router
